﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DynamicComparer;
using Shuba.Model;

namespace Shuba.Web.bulk_upload
{
    public partial class branch_rollout_mobile_version_list : basePage
    {
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultFocus = btnAdd.ClientID;
            this.Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("MSTR_BRANCH_ROLLOUT_MOBILE");

            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitRegionList();
                initVersion();
                InitClusterList(ddlRegion.SelectedValue);

                InitSort();
                BindData();

                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_ROLLOUT_MOBILE");

                if (IsAdd)
                {
                    btnAdd.Enabled = true;
                    btnUpload.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = false;
                    btnUpload.Enabled = false;
                }
            }
        }

        private void BindData()
        {
            Shuba.Business.branch_rollout_mobile_version bl = new Shuba.Business.branch_rollout_mobile_version();
            List<branch_rollout_versionInfo> list;

            string RegionID = ddlRegion.SelectedValue;
            string ClusterID = ddlCluster.SelectedValue;
            if (RegionID == "ALL") RegionID = "%";
            if (ClusterID == "ALL") ClusterID = "%";

            list = bl.GetList(ddlVersion.SelectedValue, ClusterID, RegionID); ;
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<branch_rollout_versionInfo> comparer = new DynamicComparer<branch_rollout_versionInfo>(sort);
                list.Sort(comparer);
            }

            gvbranch_rollout_version.DataSource = list;
            gvbranch_rollout_version.DataBind();

            if (IsEdit || IsDelete)
            {
                gvbranch_rollout_version.Columns[gvbranch_rollout_version.Columns.Count - 1].Visible = true;
            }
            else
            {
                gvbranch_rollout_version.Columns[gvbranch_rollout_version.Columns.Count - 1].Visible = false;
            }

            if (IsChecker)
            {
                BindApprovalData();
                if (ApprovalGrid.Rows.Count > 0) 
                { 
                    ApprovalPnl.Visible = true; 
                } 
                else 
                { 
                    ApprovalPnl.Visible = false; 
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void gvbranch_rollout_version_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            string[] args = e.CommandArgument.ToString().Split('~');
            switch (e.CommandName)
            {   
                case "Edit":
                    Response.Redirect("branch_rollout_mobile_version_edit.aspx?a=ed&brc=" + args[0] + "&vr=" + args[1]);
                    //Response.Redirect("branch_rollout_version_approval.aspx?a=ed&id=" + args[0] + "~" + args[1] +"~"+ ddlRegion.SelectedValue +"~"+ ddlCluster.SelectedValue);
                    break;
                case "Remove":
                    string cmmnd = e.CommandArgument.ToString();
                    string[] val = cmmnd.Split('~');
                    var bsRoll = new Shuba.Business.branch_rollout_mobile_version();
                    Shuba.Model.branch_rollout_versionInfo _ci = bsRoll.Get(val[0],val[1]);
                    _ci.update_by = HttpContext.Current.User.Identity.Name;
                    _ci.update_date = DateTime.Now;
                    _ci.ActType = "DELETE";
                    try
                    {
                        bsRoll.Save(_ci);
                        AddLog("DELETE", "DELETE BRANCH ROLLOUT MOBILE");
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message.ToString();
                        ErrBox.Visible = true;
                        ErrMsg.Text = msg;
                    }

                    if (msg == "") BindData(); // RestartPage();

                    break;
            }
        }

        protected void gvbranch_rollout_version_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvbranch_rollout_version.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvbranch_rollout_version_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvbranch_rollout_version.PageIndex = 0;
            BindData();
        }

        protected void gvbranch_rollout_version_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");
                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");

                if (IsEdit)
                {
                    btnEdit.Enabled = true;
                    btnDelete.Enabled = true;
                }
                else
                {
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                }
                if (e.Row.Cells[5].Text.ToLower().Contains("01 jan 2009")) e.Row.Cells[5].Text = "";
            }
        }

        private void InitRegionList()
        {
            var _Region = new Shuba.Business.Regional();

            ddlRegion.DataTextField = "RegionalName";
            ddlRegion.DataValueField = "RegionalID";
            ddlRegion.DataSource = _Region.GetAll();
            ddlRegion.DataBind();

            if (ddlRegion.Items.Count > 1)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "ALL";
                ListAll.Text = " = ALL REGION = ";

                ddlRegion.Items.Insert(0, ListAll);
            }

            /*
            var _Region = new Shuba.Business.branch_rollout_version();
            ddlRegion.Items.Clear();
            ddlRegion.Items.Add(new ListItem("- SELECT -", ""));
            List<string> list = _Region.getRegion();
            foreach (string info in list)
            {
                string[] value = info.Split('~');
                ddlRegion.Items.Add(new ListItem(info, value[0]));
            }

            /*ddlRegion.DataSource = _Region.GetList("%", Session["UnitID"].ToString(), HttpContext.Current.User.Identity.Name, ConfigurationManager.AppSettings["app.code"]);
             if (ddlRegion.Items.Count > 1)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "ALL";
                ListAll.Text = " = ALL REGION = ";

                ddlRegion.Items.Insert(0, ListAll);
            }*/
        }

        protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitClusterList(ddlRegion.SelectedValue);
        }

        private void InitClusterList(string RegionalID)
        {
            var _Cluster = new Shuba.Business.Cluster();

            if (RegionalID == "ALL") RegionalID = "%";

            ddlCluster.DataTextField = "ClusterName";
            ddlCluster.DataValueField = "ClusterID";
            ddlCluster.DataSource = _Cluster.GetListByRegion(RegionalID);
            ddlCluster.DataBind();

            if (ddlCluster.Items.Count > 1)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "ALL";
                ListAll.Text = " = ALL CLUSTER = ";
                ddlCluster.Items.Insert(0, ListAll);
            }

            /*
            var _Cluster = new Shuba.Business.branch_rollout_version();
            ddlCluster.Items.Clear();
            ddlCluster.Items.Add(new ListItem("- SELECT -", ""));

            List<string> list = _Cluster.getCluster(RegionalID);
            foreach (string info in list)
            {
                string[] value = info.Split('~');
                ddlCluster.Items.Add(new ListItem(info, value[0]));
            }
            //ddlCluster.DataSource = _Cluster.GetListByRegion(RegionalID, Session["UnitID"].ToString(), HttpContext.Current.User.Identity.Name, ConfigurationManager.AppSettings["app.code"]);
            if (ddlCluster.Items.Count > 1)
            {
                ddlCluster.Items.Add(new ListItem("ALL", "ALL"));
            }
            */
        }

        private void initVersion()
        {
            var bsRollout = new Shuba.Business.branch_rollout_mobile_version();
            ddlVersion.Items.Clear();
            ddlVersion.Items.Add(new ListItem("- SELECT -", ""));

            List<string> list = bsRollout.getVersion();
            foreach (string info in list)
            {
                ddlVersion.Items.Add(new ListItem(info, info));
            }
        }

        //================APPROVAL==========

        private void BindApprovalData()
        {
            var BI = new Shuba.Business.branch_rollout_mobile_version();
            List<branch_rollout_versionInfo> list = BI.GetListApproval(HttpContext.Current.User.Identity.Name);

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<branch_rollout_versionInfo> comparer = new DynamicComparer<branch_rollout_versionInfo>(sort);
                list.Sort(comparer);
            }
            
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx2"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                
                if (chkItemSelect.Checked)
                {
                    string branch_id = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                    string version = ApprovalGrid.DataKeys[row.RowIndex].Values["version"].ToString();
                    Approve(branch_id,version, true);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "ApproveAlert").ToString();
            BindData();
            Alert(msg);
        }

        protected void btnApproveAll_Click(object sender, EventArgs e)
        {
            int errorCount = 0, successCount = 0;
            var bussRoll = new Shuba.Business.branch_rollout_mobile_version();
            List<branch_rollout_versionInfo> list = bussRoll.GetListApproval(HttpContext.Current.User.Identity.Name);
            foreach (branch_rollout_versionInfo info in list)
            {
                try
                {
                    Approve(info.BranchID, info.version, true);
                    successCount++;
                }
                catch (Exception)
                {
                    errorCount++;
                }
            }
            if (successCount > 0 || errorCount > 0)
            {
                msg = "Approval Notification \\n\\n Total Record to Approve : " + list.Count + " Record(s)\\nSuccessfully Approved : " + successCount.ToString() + " Record(s)\\nFailed to Approve : " + errorCount.ToString() + " Record(s)";
            }
            BindData();
            Alert(msg);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string branch_id = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                    string version = ApprovalGrid.DataKeys[row.RowIndex].Values["version"].ToString();
                    Approve(branch_id, version, false);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
        }

        protected void btnRejectAll_Click(object sender, EventArgs e)
        {
            int errorCount = 0, successCount = 0;
            var bussRoll = new Shuba.Business.branch_rollout_mobile_version();
            List<branch_rollout_versionInfo> list = bussRoll.GetListApproval(HttpContext.Current.User.Identity.Name);
            foreach (branch_rollout_versionInfo info in list)
            {
                try
                {
                    Approve(info.BranchID, info.version, false);
                    successCount++;
                }
                catch (Exception)
                {
                    errorCount++;
                }
            }
            if (successCount > 0 || errorCount > 0)
            {
                msg = "Rejection Notification \\n\\n Total Record to Reject : " + list.Count + " Record(s)\\nSuccessfully Rejected : " + successCount.ToString() + " Record(s)\\nFailed to Reject : " + errorCount.ToString() + " Record(s)";
            }
            BindData();
            Alert(msg);
        }

        private void Approve(string branch_id, string version, bool IsApprove)
        {
            string ActType;

            var bsRoll = new Shuba.Business.branch_rollout_mobile_version();
            var info = new Shuba.Model.branch_rollout_versionInfo();

            info = bsRoll.GetApprovalByID(branch_id, version);
            ActType = info.ActType;
            info.update_by = HttpContext.Current.User.Identity.Name;
            info.update_date = DateTime.Now;
            try
            {
                if (IsApprove)
                {
                    bsRoll.Approve(branch_id,version, ActType);
                    AddLog("APPROVAL", "APPROVE BRANCH ROLLOUT MOBILE VERSION");
                }
                else
                {
                    bsRoll.Reject(branch_id,version);
                    AddLog("REJECT", "REJECT BRANCH ROLLOUT  MOBILE VERSION");
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message.Replace("'", "").Replace("\"", ""));
            }
        }
    }
}
